package com.ja.openchat.viewmodels;

import android.app.Application;
import android.graphics.Bitmap;

import androidx.annotation.NonNull;
import androidx.databinding.ObservableField;

import com.google.gson.JsonObject;
import com.zy.openchat.core.manager.TelegramManager;
import com.zy.openchat.core.manager.TgResultBlock;
import com.zy.openchat.core.model.group.ChatInviteLink;
import com.zy.openchat.core.model.message.ChatInfo;
import com.zy.openchat.core.model.user.UserInfo;

import net.glxn.qrgen.android.QRCode;

import org.apache.commons.lang3.StringUtils;

import java.util.Map;

import me.goldze.mvvmhabit.base.BaseViewModel;
import me.goldze.mvvmhabit.binding.command.BindingAction;
import me.goldze.mvvmhabit.binding.command.BindingCommand;
import me.goldze.mvvmhabit.bus.event.SingleLiveEvent;


public class QrCodeModel extends BaseViewModel {
    //用户名的绑定
    public ObservableField<String> userName = new ObservableField<>(UserInfo.getUserInfo().displayName());
    public ObservableField<String> userNameSub = new ObservableField<>(StringUtils.isEmpty(UserInfo.getUserInfo().username) ? "" : ("@" + UserInfo.getUserInfo().username));

    //二维码图片
    public ObservableField<Bitmap> myBitmap = new ObservableField<>(QRCode.from(UserInfo.getUserInfo().qrString()).withSize(800, 800).bitmap());
    //封装一个界面发生改变的观察者
    public UIChangeObservable uc = new UIChangeObservable();

    public QrCodeModel(@NonNull Application application) {
        super(application);
    }

    public class UIChangeObservable {
        //密码开关观察者
        public SingleLiveEvent<Boolean> onQrCodeSaveEvent = new SingleLiveEvent<>();
        public SingleLiveEvent<Boolean> onQrCodeShareEvent = new SingleLiveEvent<>();
    }

    //保存按钮的点击事件
    public BindingCommand saveOnClickCommand = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            uc.onQrCodeSaveEvent.setValue(uc.onQrCodeSaveEvent.getValue() == null || !uc.onQrCodeSaveEvent.getValue());
        }
    });
    //分享按钮的点击事件
    public BindingCommand shareOnClickCommand = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            uc.onQrCodeShareEvent.setValue(uc.onQrCodeShareEvent.getValue() == null || !uc.onQrCodeShareEvent.getValue());
        }
    });


    public void genrateLink(ChatInfo chatInfo){
        TelegramManager.getTelegramManager().generateChatInviteLink(getApplication(), chatInfo.id, new TgResultBlock<ChatInviteLink>() {
            @Override
            public void onResult(Map<String, Object> request, JsonObject response, ChatInviteLink obj) {
                if(obj!=null){
                    myBitmap.set(QRCode.from(obj.invite_link).withSize(800, 800).bitmap());
                }
            }

            @Override
            public void onTimeout(Map<String, Object> request) {

            }
        });
    }

}
